from django.contrib import admin
from .models import Server, CDNDomain, RequestUrl, AutoTask, TaskExecutionResult, ManualPreheat
from django.utils.html import format_html
from django.urls import reverse

class ServerAdmin(admin.ModelAdmin):
    """服务器模型管理类"""
    list_display = ('ip', 'ssh_port', 'remark', 'created_time', 'updated_time')
    search_fields = ('ip', 'remark')
    list_filter = ('created_time',)
    ordering = ('-created_time',)
    
class CDNDomainAdmin(admin.ModelAdmin):
    """CDN域名模型管理类"""
    list_display = ('domain', 'vendor', 'project', 'created_time', 'updated_time')
    search_fields = ('domain', 'project')
    list_filter = ('vendor', 'created_time')
    ordering = ('-created_time',)
    
class RequestUrlAdmin(admin.ModelAdmin):
    """请求地址模型管理类"""
    list_display = ('full_url', 'cdn_domain', 'created_time')
    search_fields = ('url', 'cdn_domain__domain')
    list_filter = ('cdn_domain', 'created_time')
    ordering = ('-created_time',)
    
    def full_url(self, obj):
        return format_html(f"{obj.cdn_domain.domain}{obj.url}")
    full_url.short_description = '完整URL'

class AutoTaskAdmin(admin.ModelAdmin):
    """自动任务模型管理类"""
    list_display = ('name', 'task_type', 'interval', 'is_active', 'created_time', 'updated_time', 'view_results')
    search_fields = ('name',)
    list_filter = ('task_type', 'is_active', 'created_time')
    ordering = ('-created_time',)
    filter_horizontal = ('servers', 'request_urls')
    
    def view_results(self, obj):
        url = reverse('admin:preheat_taskexecutionresult_changelist') + f'?task__id={obj.id}'
        return format_html('<a href="{}">查看执行结果</a>', url)
    view_results.short_description = '执行结果'

class TaskExecutionResultAdmin(admin.ModelAdmin):
    """任务执行结果模型管理类"""
    list_display = ('task', 'execution_time', 'success', 'failed_urls_preview')
    search_fields = ('task__name',)
    list_filter = ('success', 'execution_time')
    ordering = ('-execution_time',)
    readonly_fields = ('task', 'execution_time', 'success', 'failed_urls')
    
    def failed_urls_preview(self, obj):
        if obj.failed_urls:
            urls = obj.failed_urls.split('\n')
            if len(urls) <= 3:
                return format_html('<br>'.join(urls))
            else:
                preview = '<br>'.join(urls[:3]) + f'<br>... 共 {len(urls)} 个失败URL'
                return format_html(preview)
        return ''
    failed_urls_preview.short_description = '失败URL预览'

class ManualPreheatAdmin(admin.ModelAdmin):
    """手动预热模型管理类"""
    list_display = ('id', 'status', 'created_time', 'completed_time', 'failed_urls_preview')
    search_fields = ('id',)
    list_filter = ('status', 'created_time')
    ordering = ('-created_time',)
    filter_horizontal = ('servers', 'request_urls')
    readonly_fields = ('id', 'created_time', 'completed_time', 'status', 'failed_urls')
    
    def failed_urls_preview(self, obj):
        if obj.failed_urls:
            urls = obj.failed_urls.split('\n')
            if len(urls) <= 3:
                return format_html('<br>'.join(urls))
            else:
                preview = '<br>'.join(urls[:3]) + f'<br>... 共 {len(urls)} 个失败URL'
                return format_html(preview)
        return ''
    failed_urls_preview.short_description = '失败URL预览'

# 注册模型到admin站点
admin.site.register(Server, ServerAdmin)
admin.site.register(CDNDomain, CDNDomainAdmin)
admin.site.register(RequestUrl, RequestUrlAdmin)
admin.site.register(AutoTask, AutoTaskAdmin)
admin.site.register(TaskExecutionResult, TaskExecutionResultAdmin)
admin.site.register(ManualPreheat, ManualPreheatAdmin)
